<template>
  <div class="article-management">
    <h2>文章管理</h2>
    <table>
      <thead>
        <tr>
          <th>文章标题</th>
          <th>分类</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="article in articles" :key="article.id">
          <td>{{ article.title }}</td>
          <td>{{ article.category }}</td>
          <td>
            <button @click="viewArticleDetails(article.id)">查看</button>
            <button @click="editArticle(article.id)">编辑</button>
            <button @click="deleteArticle(article.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页控制 -->
    <div class="pagination">
      <button @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      articles: [],  // 存储文章数据
      currentPage: 1, // 当前页码
      pageSize: 10,   // 每页文章数
      totalArticles: 0, // 总文章数
      totalPages: 0,  // 总页数
    };
  },
  mounted() {
    this.loadArticles();
  },
  methods: {
    // 加载文章列表
    async loadArticles() {
      try {
        const response = await axios.get('http://localhost:9090/posts', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize
          }
        });
        this.articles = response.data.data.map(article => ({
          ...article,
          id: article.ID, // 确保字段 ID 转换为 id
          category: this.getCategoryName(article.category_id) // 显示分类名称
        }));
        this.totalArticles = response.data.total;
        this.totalPages = Math.ceil(this.totalArticles / this.pageSize);
      } catch (error) {
        console.error('加载文章失败', error);
        alert('加载文章失败');
      }
    },

    // 获取分类名称
    getCategoryName(category_id) {
      const categories = [
        { id: 1, name: 'java' },
        { id: 2, name: 'Python' },
        { id: 3, name: 'Kotlin' }
      ];
      const category = categories.find(c => c.id === category_id);
      return category ? category.name : 'GoLang';
    },

    // 查看文章详情
    viewArticleDetails(id) {
      console.log('查看文章详情 ID:', id);
      this.$router.push(`/article/detail/${id}`);
    },

    // 编辑文章（跳转到编辑页面）
    editArticle(id) {
      console.log('编辑文章 ID:', id);
      this.$router.push(`/article/edit/${id}`);
    },

    // 删除文章
    async deleteArticle(id) {
      console.log('删除文章 ID:', id);
      try {
        await axios.delete(`http://localhost:9090/posts/${id}`);
        this.articles = this.articles.filter((article) => article.id !== id);
        alert('文章删除成功');
      } catch (error) {
        console.error('删除文章失败', error);
        alert('删除文章失败');
      }
    },

    // 更改页码
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        this.loadArticles();
      }
    }
  }
};
</script>

<style scoped>
.article-management {
  width: 80%;
  margin: 20px auto;
}

h2 {
  text-align: center;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  padding: 10px;
  text-align: left;
}

button {
  padding: 5px 10px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
  margin-right: 10px;
}

button:hover {
  background-color: #34a77b;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination button {
  padding: 5px 15px;
  margin: 0 5px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

.pagination button[disabled] {
  background-color: #ddd;
  cursor: not-allowed;
}

.pagination span {
  line-height: 30px;
}
</style>
